<template>
	<image :src="realPath" mode="scaleToFill" :style="stylesResult" :show-menu-by-longpress="showMenuByLongpress"></image>
</template>

<script>
const { assets } = require('@/config');
import cce_toolkit from '@/utils/cce_toolkit';

export default {
	data() {
		return {
			realPath: '',
			width: 0,
			height: 0,
			assets
		};
	},
	props: {
		src: {
			type: String,
			default: ''
		},
		styles: {
			type: String,
			default: ''
		},
		showMenuByLongpress: {
			type: Boolean,
			default: false
		}
	},
	computed: {
		stylesResult() {
			return 'width:' + this.width + ';' + 'height:' + this.height + ';' + this.styles;
		}
	},
	watch: {
		src(newSrc, oldSrc) {
			this.handleImgFn(newSrc);
		}
	},
	mounted() {
		this.handleImgFn(this.src);
	},
	methods: {
		handleImgFn(newValue) {
			const globalSource = getApp().globalData.cce_loaded_images;

			if (!globalSource.get(newValue)) {
				this.downloadImgFn(newValue);
				return;
			}

			const { path, serverPath, width = 0, height = 0, type } = globalSource.get(newValue);
			if (!width || !height) {
				this.downloadImgFn(newValue);
				return;
			}
			this.realPath = path || serverPath;
			this.width = width + 'rpx';
			this.height = height + 'rpx';
		},
		//尝试二次获取源地址
		downloadImgFn(path) {
			const _self = this;
			const judgePath = path.includes('//') ? `${path}` : `${assets}${path}`;
			uni.getImageInfo({
				src: judgePath,
				success: function(imageInfo) {
					const value = Object.assign(imageInfo, {
						originPath: path,
						serverPath: judgePath
					});
					const checkIsExist = getApp().globalData['cce_loaded_images'];
					if (cce_toolkit.verify_type(checkIsExist) !== 'Map') {
						getApp().globalData['cce_loaded_images'] = new Map();
					}
					getApp().globalData.cce_loaded_images.set(value['originPath'], value);
					_self.realPath = imageInfo.path;
					_self.width = imageInfo.width + 'rpx';
					_self.height = imageInfo.height + 'rpx';
				},
				fail: function(e) {
					//加载失败，则返回原始路径
					console.warn(e);
				},
				complete: function(e) {
					console.log(e);
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped></style>
